package com.pirestupppai.widgets.dialog;

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.pirestupppai.R;
import com.pirestupppai.adapter.SearchTagAdapter;
import com.pirestupppai.base.BaseAdapter;
import com.pirestupppai.base.BaseDialog;
import com.pirestupppai.base.BaseStatus;
import com.pirestupppai.bean.TagItem;
import com.pirestupppai.common.Constant;
import com.pirestupppai.network.NetworkRequest;
import com.pirestupppai.network.TupaiSubscriber;
import com.pirestupppai.utils.SharedPreferenceUtil;
import com.pirestupppai.utils.Utils;
import com.pirestupppai.widgets.view.FlowTagLayout;
import com.pirestupppai.widgets.view.LoadMoreFooter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;

/**
 * 发动态搜索标签
 *
 * author: xiaoluo
 * date: 2017/6/20 15:34
 */
public class SearchTagDialog extends BaseDialog {

    @BindView(R.id.clear_btn)
    ImageView clearBtn;
    @BindView(R.id.search_btn)
    TextView searchBtn;
    @BindView(R.id.search_et)
    EditText searchEt;
    @BindView(R.id.empty_view)
    TextView emptyView;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.default_layout)
    LinearLayout defaultLayout;
    @BindView(R.id.search_popular_layout)
    FlowTagLayout popularLayout;
    @BindView(R.id.search_history_layout)
    FlowTagLayout hisLayout;

    private OnSearchResultListener mListener;
    private List<String> mHistoryList = new ArrayList<>();
    private List<String> mPopularList = new ArrayList<>();

    private LoadMoreFooter mFooterView;
    private SearchTagAdapter mSearchTagAdapter;
    private LinearLayoutManager mLinearLayoutManager;

    private int mPosition = 0;  // 列表最后一位
    private int mPage = 1;
    private int mSize = 20;
    private boolean hasMore = true;
    private String mSearchKey;
    private List<TagItem> mSearchTagList = new ArrayList<>();

    public SearchTagDialog(Context context, OnSearchResultListener listener) {
        super(context, R.style.SearchDialog);
        mListener = listener;
    }

    @Override
    public boolean atBottom() {
        return false;
    }

    @Override
    public int loadParentLayout() {
        return R.layout.dialog_search_tag;
    }

    @Override
    public void initViews() {
        mFooterView = new LoadMoreFooter(mContext);
        mSearchTagAdapter = new SearchTagAdapter(mContext, mSearchTagList);
        mSearchTagAdapter.addFooterView(mFooterView);
        mLinearLayoutManager = new LinearLayoutManager(mContext);
        mLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        recyclerView.setLayoutManager(mLinearLayoutManager);
        recyclerView.setAdapter(mSearchTagAdapter);
        recyclerView.setHasFixedSize(true);

        initLogic();
    }

    @Override
    public void initListeners() {
        searchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(searchEt.getText().toString().trim())) {
                    Utils.showToast("请输入内容");
                    return;
                }
                saveAndSearch(searchEt.getText().toString().trim());
            }
        });

        clearBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchEt.setText("");
            }
        });

        searchEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 0) {
                    defaultLayout.setVisibility(View.VISIBLE);
                    recyclerView.setVisibility(View.GONE);
                }
            }
        });

        searchEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String searchKey = searchEt.getText().toString().trim();
                    if (TextUtils.isEmpty(searchKey)) {
                        Utils.showToast("请输入内容");
                        return false;
                    }
                    if (searchKey.length() > 15) {
                        Utils.showToast("标签字数小于15");
                        return false;
                    }
                    saveAndSearch(searchKey);
                    hideInputPanel();
                    return true;
                }
                return false;
            }
        });

        emptyView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mListener.onResult(searchEt.getText().toString().trim());
                dismiss();
            }
        });

        // 监听到达底部事件
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //到达底部时,加载更多
                int lastVisiblePosition = mLinearLayoutManager.findLastCompletelyVisibleItemPosition() + 1;
                if (mLinearLayoutManager.getChildCount() > 0
                        && mLinearLayoutManager.getItemCount() >= mLinearLayoutManager.getChildCount()
                        && lastVisiblePosition >= mLinearLayoutManager.getItemCount()
                        && dy > 0) {
                    mPosition = lastVisiblePosition;

                    if (hasMore) {
                        mFooterView.setStatus(LoadMoreFooter.Status.LOADING);
                        searchTag(BaseStatus.LOADMORE);
                    }
                }
            }
        });

        mSearchTagAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                mListener.onResult(mSearchTagList.get(position).getText());
                dismiss();
            }
        });
    }

    private void initLogic() {
        loadHistoryData();
        loadPopularData();
    }

    /**
     * 获取热搜数据
     */
    private void loadPopularData() {
        if (Constant.popularTags != null && Constant.popularTags.size() != 0) {
            createPopularView();
        } else {
            NetworkRequest.getInstance().getHomeTagList(1, 10,
                    new TupaiSubscriber<List<TagItem>>(mContext) {
                        @Override
                        protected void requestSuccess(List<TagItem> tagItems) {
                            if (tagItems != null && tagItems.size() != 0) {
                                for (int i = 0; i < tagItems.size(); i++) {
                                    mPopularList.add(tagItems.get(i).getText());
                                }
                                Constant.popularTags.addAll(mPopularList);
                                createPopularView();
                            }
                        }

                        @Override
                        protected void requestError(String error) {

                        }
                    });
        }
    }

    private void createPopularView() {
        if (Constant.popularTags == null || Constant.popularTags.size() == 0) {
            return;
        }
        LinearLayout.LayoutParams tagLp = new LinearLayout.LayoutParams(
                WRAP_CONTENT, WRAP_CONTENT);
        tagLp.setMargins(Utils.dpToPx(mContext, 0), Utils.dpToPx(mContext, 0),
                Utils.dpToPx(mContext, 10), Utils.dpToPx(mContext, 10));
        for (int i = 0; i < Constant.popularTags.size(); i++) {
            final TextView tag = new TextView(mContext);
            tag.setText(Constant.popularTags.get(i));
            tag.setTextSize(13);
            tag.setPadding(Utils.dpToPx(mContext, 10), Utils.dpToPx(mContext, 9), Utils.dpToPx(mContext, 10), Utils.dpToPx(mContext, 9));
            tag.setTextColor(mContext.getResources().getColor(R.color.gray_text));
            tag.setBackgroundResource(R.drawable.selector_search_flow_tag);
            tag.setClickable(true);
            tag.setTag(tag.getText().toString());

            tag.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mListener.onResult((String) tag.getTag());
                    dismiss();
                }
            });

            popularLayout.addView(tag, tagLp);
        }
    }

    /**
     * 获取历史数据
     */
    private void loadHistoryData() {
        mHistoryList.clear();
        int historySize = SharedPreferenceUtil.sp.getInt(Constant.SPKey.HISTORY_SIZE, 0);
        if (historySize <= 0) {
            return;
        }

        for (int i = 0; i < historySize; i++) {
            mHistoryList.add(SharedPreferenceUtil.sp.getString(Constant.SPKey.HISTORY_ITEM + i, null));
        }

        LinearLayout.LayoutParams tagLp = new LinearLayout.LayoutParams(
                WRAP_CONTENT, WRAP_CONTENT);
        tagLp.setMargins(Utils.dpToPx(mContext, 0), Utils.dpToPx(mContext, 5),
                Utils.dpToPx(mContext, 10), Utils.dpToPx(mContext, 5));
        for (int i = 0; i < mHistoryList.size(); i++) {
            final TextView tag = new TextView(mContext);
            tag.setText(mHistoryList.get(i));
            tag.setTextSize(13);
            tag.setPadding(Utils.dpToPx(mContext, 10), Utils.dpToPx(mContext, 9), Utils.dpToPx(mContext, 10), Utils.dpToPx(mContext, 9));
            tag.setTextColor(mContext.getResources().getColor(R.color.gray_text));
            tag.setBackgroundResource(R.drawable.selector_search_flow_tag);
            tag.setClickable(true);
            tag.setTag(tag.getText().toString());

            tag.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mListener.onResult((String) tag.getTag());
                    dismiss();
                }
            });

            hisLayout.addView(tag, tagLp);
        }
    }


    /**
     * 保存并搜索
     */
    private void saveAndSearch(String searchKey) {
        defaultLayout.setVisibility(View.GONE);

        searchEt.setSelection(searchKey.length());
        hideInputPanel();

        boolean isInHistory = false;
        if (mHistoryList.size() != 0) {
            for (int i = 0; i < mHistoryList.size(); i++) {
                if (searchKey.equals(mHistoryList.get(i))) {
                    isInHistory = true;
                    mHistoryList.remove(i);
                    mHistoryList.add(0, searchKey);
                    break;
                }
            }
        }

        if (!isInHistory) {
            if (mHistoryList.size() >= 10) {
                mHistoryList.remove(mHistoryList.size() - 1);
            }
            mHistoryList.add(0, searchKey);
        }

        SharedPreferenceUtil.editor.putInt(Constant.SPKey.HISTORY_SIZE, mHistoryList.size());
        for (int i = 0; i < mHistoryList.size(); i++) {
            SharedPreferenceUtil.editor.remove(Constant.SPKey.HISTORY_ITEM + i);
            SharedPreferenceUtil.editor.putString(Constant.SPKey.HISTORY_ITEM + i, mHistoryList.get(i));
        }
        SharedPreferenceUtil.editor.apply();

        mSearchKey = searchKey;
        searchTag(BaseStatus.REFRESH);
    }

    private void searchTag(final BaseStatus status) {
        defaultLayout.setVisibility(View.GONE);
        if (status == BaseStatus.REFRESH) {
            hasMore = true;
            mPage = 1;
        } else {
            mPage++;
        }
        NetworkRequest.getInstance().searchTag(mSearchKey, mPage, mSize, mContext,
                new TupaiSubscriber<List<TagItem>>(mContext) {
                    @Override
                    protected void requestSuccess(List<TagItem> tagItems) {
                        if (tagItems != null && tagItems.size() != 0) {
                            if (status == BaseStatus.REFRESH) {
                                emptyView.setVisibility(View.GONE);
                                recyclerView.setVisibility(View.VISIBLE);
                                mSearchTagList.clear();
                                mSearchTagList.addAll(tagItems);
                                mSearchTagAdapter.notifyDataSetChanged();
                            } else {
                                mSearchTagList.addAll(tagItems);
                                mSearchTagAdapter.notifyItemInserted(mPosition);
                            }
                        } else if (status == BaseStatus.REFRESH) {
                            emptyView.setVisibility(View.VISIBLE);
                            recyclerView.setVisibility(View.GONE);
                        }

                        if (tagItems.size() < mSize) {
                            mFooterView.setStatus(LoadMoreFooter.Status.THE_END);
                            hasMore = false;
                        }
                    }

                    @Override
                    protected void requestError(String error) {
                        if (status == BaseStatus.LOADMORE) {
                            mPage--;
                        }
                    }
                });
    }

    /**
     * 隐藏键盘
     */
    private void hideInputPanel() {
        // 隐藏软键盘
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(searchEt.getWindowToken(), 0);
    }

    public interface OnSearchResultListener {
        void onResult(String tag);
    }
}
